package com.c6906.vdam.das.listener;

import com.c6906.vdam.das.service.VehicleStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

public class ParkingKeyExpirationListener extends KeyExpirationEventMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(ParkingKeyExpirationListener.class);

    private final VehicleStatusService vehicleStatusService;
    private final StringRedisTemplate stringRedisTemplate;

    public ParkingKeyExpirationListener(RedisMessageListenerContainer listenerContainer, VehicleStatusService vehicleStatusService, StringRedisTemplate stringRedisTemplate) {
        super(listenerContainer);
        this.vehicleStatusService = vehicleStatusService;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        if (key.startsWith("vehicle:") && key.endsWith(":shutdown")) {
            // 加一把防重复锁
            String lockKey = "lock:expire:" + key;
            Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", java.time.Duration.ofSeconds(30));
            if (Boolean.TRUE.equals(success)) {
                // 拿到锁，执行业务
                try {
                    vehicleStatusService.onRedisExpired(key);
                } catch (Exception e) {
                    logger.error("处理车辆停车过期业务异常, key={}", key, e);
                }
            } else {
                logger.debug("重复触发过期事件, 已被其他节点处理, 忽略: {}", key);
            }
        }
    }
}
